package com.boyon.system.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boyon.common.exection.BusinessException;
import com.boyon.common.tools.ImageTool;
import com.boyon.common.tools.RondomTool;
import com.boyon.common.tools.RondomType;
import com.boyon.common.tools.StringTool;
import com.boyon.redis.adapter.JedisAdapter;
import com.boyon.redis.wrap.JedisWrap;
import com.boyon.system.domain.Verification;

/**
 * ClassName:VerificationService <br/>
 * Function: 验证码通用业务处理类. <br/>
 * Date: 2018年3月17日 下午9:41:30 <br/>
 * 
 * @author sunshulin
 * @version
 * @since JDK 1.8
 * @see
 */
@Service
public class VerificationService {

	@Autowired
	private JedisAdapter jedisAdapter;

	/**
	 * createVerification:生成验证码图片
	 * 
	 * @author sunshulin
	 * @param width
	 * @param height
	 * @param size
	 * @param unique
	 * @return
	 * @since JDK 1.8
	 */
	public Verification createVerification(int width, int height, int size,
			String unique) {
		String verifyCode = RondomTool.createCode(size, RondomType.full);
		String baseImageInfo = ImageTool.createCodeImg(width, height,
				verifyCode);
		JedisWrap jedisWrap = jedisAdapter.getResource();
		try {
			jedisWrap.selectDatabase(11);
			jedisWrap.set(unique, verifyCode);
			jedisWrap.expire(unique, 60);
		} finally {
			jedisWrap.release();
		}
		return new Verification(verifyCode, baseImageInfo, unique);
	}

	/**
	 * 
	 * getVerification:获取系统验证码. <br/>
	 * 
	 * @author sunshulin
	 * @param unique
	 * @return
	 * @since JDK 1.8
	 */
	public boolean validator(String unique, String code) {
		validatorVerification(unique, code);
		JedisWrap jedisWrap = jedisAdapter.getResource();
		try {
			jedisWrap.selectDatabase(11);
			String originValue = jedisWrap.get(unique);
			if (!StringTool.isNotNull(originValue)) {
				throw BusinessException.builder(0, "验证码失效或不存在");
			}
			if (!originValue.equalsIgnoreCase(code)) {
				throw BusinessException.builder(0, "验证码不正确");
			}
		} finally {
			jedisWrap.delete(unique);
			jedisWrap.release();
		}
		return true;
	}

	/**
	 * 
	 * validatorVerification:验证. <br/>
	 * 
	 * @author sunshulin
	 * @param unique
	 * @param code
	 * @since JDK 1.8
	 */
	public void validatorVerification(String unique, String code) {
		if (!StringTool.isNotNull(unique)) {
			throw BusinessException.builder(0, "唯一标识码不存在");
		}
		if (!StringTool.isNotNull(code)) {
			throw BusinessException.builder(0, "输入验证码不存在");
		}
	}
}
